﻿package com.agileai.miscdp.hotweb.generator.mastersub;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import com.agileai.miscdp.NoOpEntityResolver;
import com.agileai.miscdp.hotweb.domain.mastersub.MasterSubFuncModel;
import com.agileai.miscdp.hotweb.domain.mastersub.SubTableConfig;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.XmlUtil;
/**
 * Handler配置代码生成器
 */
public class MSHandlerCfgGenerator implements Generator{
	private MasterSubFuncModel funcModel = null;
	private String configFile = null;
	private String encoding = "UTF-8";
	
	public void generate() {
		try {
	        SAXReader saxReader = new SAXReader();
	        saxReader.setEntityResolver(new NoOpEntityResolver());
	        saxReader.setIncludeExternalDTDDeclarations(false);
	        saxReader.setValidation(false);
	        Document document = saxReader.read(new File(configFile));
	        
	        String listHandlerId = funcModel.getListHandlerId();
	        String listHandlerClass = funcModel.getListHandlerClass();
	        String listJspPage = funcModel.getListJspName();
	        MiscdpUtil.newHandlerConfigElement(document, listHandlerId, listHandlerClass, listJspPage);

	        String editHandlerId = funcModel.getEditHandlerId();
	        String editHandlerClass = funcModel.getEditHandlerClass();
	        String editJspPage = funcModel.getDetailJspName();
	        MiscdpUtil.newHandlerConfigElement(document, editHandlerId, editHandlerClass, editJspPage);
	        
	        List<SubTableConfig> subTableConfigList = funcModel.getSubTableConfigs();
	        for (int i=0;i < subTableConfigList.size();i++){
	        	SubTableConfig subTableConfig = subTableConfigList.get(i);
	        	String editMode = subTableConfig.getEditMode();
	        	if (SubTableConfig.LIST_DETAIL_MODE.equals(editMode)){
	    	        String handlerId = subTableConfig.getPboxHandlerId();
	    	        String andlerClass = subTableConfig.getPboxHandlerClass();
	    	        String jspPage = subTableConfig.getPboxJspName();
	    	        MiscdpUtil.newHandlerConfigElement(document, handlerId, andlerClass, jspPage);
	        	}
	        }
	        
	        XmlUtil.writeDocument(document, encoding, configFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

	public void setFuncModel(MasterSubFuncModel suFuncModel) {
		this.funcModel = suFuncModel;
	}
}
